<?php

namespace App\Models\Fee;

use App\Models\BaseModel;

class FeeAnnualChangesModel extends BaseModel
{
    public $timestamps = false;

    protected $table = 'fee_annual_changes';

    protected $fillable = [
        'shopId',
        'feeOrderNo',
        'field',
        'beforeValue',
        'afterValue',
        'createdAt',
        'createdByUid',
        'createdByName',
        'remark',
        'image',
    ];

    private array $dbChanges = [];

    public function buildChanges(string $field, int $beforeValue, int $afterValue): self
    {
        $this->dbChanges[] = ['field' => $field, 'beforeValue' => $beforeValue, 'afterValue' => $afterValue];

        return $this;
    }

    /**
     * @param string $feeOrderNo
     * @param int $userId
     * @param string $userName
     * @param int $shopId
     * @param string $remark
     * @param string $image
     * @return bool
     */
    public function batchAdd(
        string $feeOrderNo,
        int $userId,
        string $userName,
        int $shopId,
        string $remark = "",
        string $image = ""
    ): bool {
        foreach ($this->dbChanges as &$v) {
            $v['shopId']        = $shopId;
            $v['feeOrderNo']    = $feeOrderNo;
            $v['createdAt']     = time();
            $v['createdByUid']  = $userId;
            $v['createdByName'] = $userName;
            $v["remark"]        = $remark;
            $v["image"]         = $image;
        }

        return self::query()->insert($this->dbChanges);
    }

    public function getContentAttribute(): string
    {
        $str = '';
        switch ($this->field) {
            case "endTime":
                $day = ceil(($this->afterValue - $this->beforeValue) / 86400);
                $str = "延期{$day}天";
                break;
            case "manageFee":
                $price = bcdiv($this->beforeValue - $this->afterValue, 100, 2);
                $str   = "年管理费减免{$price}元";
                break;
            case "systemFee":
                $price = bcdiv($this->beforeValue - $this->afterValue, 100, 2);
                $str   = "数字化系统年服务费减免{$price}元";
                break;
        }

        return $str;
    }
}
